/**
 * 对 array 按照 keyMapper 进行分组
 *
 * @param array 待分组数组
 * @param keyMapper 映射 array 的元素为分组后的 key
 * @example
 *
 * const products = [
 *   { name: 'apples', category: 'fruits' },
 *   { name: 'oranges', category: 'fruits' },
 *   { name: 'potatoes', category: 'vegetables' }
 * ]
 *
 * groupBy(products, p => p.category)
 * // =>  {
 *   fruits: [
 *     { name: 'apples', category: 'fruits' },
 *     { name: 'oranges', category: 'fruits' }
 *   ],
 *   vegetables: [ { name: 'potatoes', category: 'vegetables' } ]
 * }
 *
 * groupBy([6.1, 4.2, 6.3], Math.floor)
 * // => { '4': [ 4.2 ], '6': [ 6.1, 6.3 ] }
 * groupBy(['one', 'two', 'three'], p => p.length)
 * // => { '3': [ 'one', 'two' ], '5': [ 'three' ] }
 */
export function groupBy(array: any[], keyMapper: (element: any) => any): any {
  return array.reduce((group, element) => {
    const key = keyMapper(element)
    group[key] = group[key] ?? []
    group[key].push(element)
    return group
  }, {})
}

// const products = [
//   { name: 'apples', category: 'fruits' },
//   { name: 'oranges', category: 'fruits' },
//   { name: 'potatoes', category: 'vegetables' }
// ]
//
// console.log(groupBy(products, p => p.category))
// console.log(groupBy([6.1, 4.2, 6.3], Math.floor))
// console.log(groupBy(['one', 'two', 'three'], p => p.length))
